<template>
  <div class="cart">
    <el-card shadow="hover" class="cart-card">
      <el-table :data="tableData" style="width: 100%" size="small" border v-loading="loading"
        @selection-change="handleSelectionChange" ref="multipleTable">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <el-image :src="scope.row.skuUrl" style="width: 100px; height: 100px;" fit="contain"
              :preview-src-list="[scope.row.skuUrl]" />
          </template>
        </el-table-column>/
        <el-table-column prop="spuName" label="商品名称" align="center">
          <template slot-scope="scope">
            <el-link type="success" @click="redirectToSpu(scope.row.spuId)">{{
              scope.row.spuName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="skuAttribute" label="商品属性" align="center">
          <template slot-scope="scope">
            <el-tag>{{ JSON.parse(scope.row?.skuAttribute)?.color }}</el-tag>
            <el-tag>{{ JSON.parse(scope.row?.skuAttribute)?.size }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品单价￥" align="center">
          <template slot-scope="scope">
            <p class="price-show">
              {{ scope.row.salePrice }}
              <span class="price" v-if="scope.row.salePrice != scope.row.price">{{ scope.row.price }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="购买数量" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.count" :min="1" :max="10" label="购买数量" size="mini"
              @change="changeCount(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <el-result title="购物车空空如也~" subTitle="去首页逛逛吧~">
            <template slot="icon">
              <svg t="1716647113751" class="icon" viewBox="0 0 1024 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="3722" width="200" height="200">
                <path
                  d="M278.016 933.888a64.512 64.512 0 1 0 129.024 0 64.512 64.512 0 1 0-129.024 0zM940.032 569.344l49.152-263.68c2.56-14.336-6.656-28.16-20.992-30.72s-28.16 6.656-30.72 20.992l-49.152 263.68c-6.144 32.256-32.768 56.32-65.536 58.88L298.496 660.48c-32.768-206.848-57.344-354.816-73.728-445.952l-9.728-52.736c-5.12-27.648-9.216-45.568-11.776-54.272C182.272 36.352 71.168 57.344 58.88 59.904 44.544 62.976 35.328 76.8 38.4 91.136s16.896 23.552 31.232 20.48c31.744-6.656 78.848-5.12 83.456 10.752C162.816 154.624 197.12 358.912 256 728.576c8.192 51.712 51.712 89.088 103.936 89.088l540.16 2.048c14.336 0 26.112-11.776 26.112-26.112s-11.776-26.112-26.112-26.624l-540.16-2.048c-26.112 0-48.128-18.944-52.224-45.056-0.512-2.56-0.512-5.12-1.024-7.68L826.88 670.72c56.32-4.096 102.912-46.08 113.152-101.376zM757.248 933.888a64.512 64.512 0 1 0 129.024 0 64.512 64.512 0 1 0-129.024 0z"
                  fill="#E02E24" p-id="3723"></path>
                <path
                  d="M446.464 432.128l-71.168 98.304h60.928c6.656 0 12.288 5.632 12.288 12.288 0 6.656-5.632 12.288-12.288 12.288h-89.6c-7.168 0-12.288-5.632-12.288-12.288 0-2.56 1.024-5.12 2.56-7.68l72.192-97.792h-56.32c-6.656 0-12.288-5.632-12.288-12.288 0-6.656 5.632-12.288 12.288-12.288h83.968c7.168 0 12.288 5.632 12.288 12.288-0.512 2.56-1.024 5.12-2.56 7.168zM639.488 269.824l-71.168 98.304h60.928c6.656 0 12.288 5.632 12.288 12.288 0 6.656-5.632 12.288-12.288 12.288h-89.6c-7.168 0-12.288-5.632-12.288-12.288v-0.512c0-2.56 1.024-5.12 2.56-7.68l72.192-97.792h-56.32c-6.656 0-12.288-5.632-12.288-12.288 0-6.656 5.632-12.288 12.288-12.288h83.968c7.168 0 12.288 5.632 12.288 12.288-0.512 3.072-1.024 5.632-2.56 7.68zM866.304 116.736l-102.912 143.36h88.064c10.24 0 17.92 8.192 17.92 17.92 0 10.24-8.192 17.92-17.92 17.92H721.408a18.355 18.355 0 0 1-18.432-18.432v-0.512c0-4.096 1.024-7.68 3.584-10.752l104.96-142.336h-82.432c-10.24 0-17.92-8.192-17.92-17.92 0-10.24 8.192-17.92 17.92-17.92h122.368a18.355 18.355 0 0 1 18.432 18.432c0 3.584-1.024 7.168-3.584 10.24z"
                  fill="#E02E24" p-id="3724"></path>
              </svg>
            </template>
            <template slot="extra">
              <el-button type="primary" plain size="medium" @click="$router.push('/front/home')">去首页</el-button>
            </template>
          </el-result>
        </template>
      </el-table>
      <el-button @click="delSelected" style="margin-top: 10px;" type="danger" plain>批量删除</el-button>
    </el-card>
    <div style="margin-top: 10px">
      <el-row justify="space-between">
        <el-col :span="12" class="footer-line-left">
          <div style="flex: 1; color: #999; font-size: 12px">
            <div>共 <span style="color: red; font-size: 20px">{{ totalCount }}</span> 件商品</div>
            <div style="color: orange; padding-top: 5px">立即下单，享超值优惠！</div>
            <div style=" padding-top: 5px ">本单总积分 <span style="font-size: 20px;color: green;">{{ points }}</span></div>
          </div>
        </el-col>
        <el-col :span="12" class="footer-line-right">
          <div style="flex: 1;color: red; text-align: right">
            <div>
              <span>总金额</span>
              <p class="price-show">
                ￥ {{ payPrice }}
                <span class="price" v-show="payPrice != totalPrice">{{ totalPrice }}</span>
              </p>
              <el-button style="background-color: red; color: white; margin-left: 20px"
                @click="submitOrder">去结算</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getUser } from "@/utils/storage";
import { round } from "lodash";
import { deleteCartBatch } from "@/api/sCart";
import { mapState, mapActions } from "vuex"
import { mapMutations } from "vuex/dist/vuex.common.js";
import { getSpuById } from "@/api/goods";
export default {
  name: "FrontCart",
  data() {
    return {
      user: {},
      tableData: [],
      loading: false,
      multipleSelection: []
    }
  },
  computed: {
    ...mapState('sCart', ['sCartList', 'selectedList']),
    totalPrice() {
      return this.multipleSelection.reduce((total, item) => {
        return total + item.price * item.count
      }, 0)
    },
    payPrice() {
      return this.multipleSelection.reduce((total, item) => {
        return total + item.salePrice * item.count
      }, 0)
    },
    totalCount() {
      return this.multipleSelection.reduce((total, item) => {
        return total + item.count
      }, 0)
    },
    points() {
      let tmpPrice = this.multipleSelection.reduce((total, item) => {
        return total + item.salePrice * item.count
      }, 0)
      return tmpPrice / 100
    }
  },
  watch: {
    selectedList: {
      handler(newValue) {
        // console.log(newValue)
      },
      deep: true
    }
  },

  created() {
    this.user = getUser()
    if (!this.user) {
      this.$message({
        type: "warning",
        message: '请登录！'
      })
      return
    }
    this.load()
  },
  methods: {
    ...mapActions('sCart', ['getSCartListAction', 'countChange', 'delSCart', 'delSCartBatch']),
    ...mapMutations('sCart', ['setSelectedList']),
    async load() {
      this.loading = !this.loading
      await this.getSCartListAction(this.user.id);
      this.tableData = this.sCartList
      this.loading = !this.loading
    },
    async changeCount(row) {
      await this.countChange({ id: row.id, userId: this.user.id, count: row.count })
      await this.load()
    },
    async submitOrder() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: "warning",
          message: '请选择商品！'
        })
        return
      }
      this.setSelectedList(this.multipleSelection)
      this.$router.push({
        path: '/front/preOrder',
      })
    },
    async del(id) {
      await this.$confirm('确认删除商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.delSCart({ userId: this.user.id, id: id })

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => { });
      await this.load()
    },
    async delSelected() {
      let ids = this.multipleSelection.map(item => item.id)
      if (ids.length === 0) {
        this.$message({
          type: "warning",
          message: '请选择商品'
        })
        return
      }
      await this.$confirm('确认删除商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteCartBatch({ userId: this.user.id, ids: ids })
        this.$message.success('删除成功')
      });
      await this.load()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.points)
    },
    redirectToSpu(spuId) {
      getSpuById(spuId).then(res => {
        if (res.code === '0') {
          this.$store.commit('spu/setSelectedSpu', res.data)
          this.$router.push("/front/goods")
        }
      })
    }
  }
}
</script>

<style scoped>
.cart {
  margin-top: 10px;
  height: 80vh;
}

.cart-card {
  min-height: 60%;
}

.price-show {
  color: red;
  font-size: 18px;
}

.price-show .price {
  text-decoration: line-through;
  font-size: 12px;
  color: #ccc;
}

.footer-line-left {
  display: flex;
  justify-content: left;
  align-content: center;
  padding-left: 20px;
}

.footer-line-right {
  display: flex;
  justify-content: right;
  align-content: center;
  padding-right: 20px;
}
</style>
